package com.wa.nashorn;

import java.util.Map;
import org.slf4j.MDC;

public class ContextNashornScript<O> implements NashornScript<O> {
    private NashornScript<O> delegate;
    private Map<String, String> contextMap;

    public ContextNashornScript(NashornScript<O> script, Map<String, String> contextMap) {
        this.delegate = script;
        this.contextMap = contextMap;
    }

    public static <O> NashornScript<O> wrapper(NashornScript<O> script) {
        return new ContextNashornScript(script, MDC.getCopyOfContextMap());
    }

    public String getScript() {
        this.initContext();
        return this.delegate.getScript();
    }

    public O process(NashornEngineService input) {
        this.initContext();
        return this.delegate.process(input);
    }

    public void onComplete(O out) {
        this.initContext();
        this.delegate.onComplete(out);
    }

    public void onError(Exception ex) {
        this.initContext();
        this.delegate.onError(ex);
    }

    public StringBuilder getLoggerOutputBuilder() {
        this.initContext();
        return this.delegate.getLoggerOutputBuilder();
    }

    void initContext() {
        if (this.contextMap != null) {
            MDC.setContextMap(this.contextMap);
        }

    }
}
